<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="关键字" prop="searchValue">
        <el-input
          v-model="queryParams.searchValue"
          placeholder="项目名称或首字母搜索"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="服务归属" prop="serviceItems">
        <el-select
          v-model="queryParams.serviceItems"
          placeholder="请选择服务归属"
          clearable
          @change="serviceItemsQuery"
        >
          <el-option
            v-for="dict in dict.type.service_items"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="项目类别" prop="dictCode">
        <el-cascader
          :options="classList"
          placeholder="请选择项目类别"
          :props="{
            label: 'categoryName',
            value: 'categoryId',
            children: 'childList',
            emitPath: false,
          }"
          v-model="queryParams.dictCode"
          :disabled="!queryParams.serviceItems"
          filterable
          clearable
          @change="handleQuery"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择状态"
          clearable
          @change="handleQuery"
        >
          <el-option label="启用" :value="0" />
          <el-option label="禁用" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否常用项目" prop="isCommon">
        <el-radio-group v-model="queryParams.isCommon" @input="handleQuery">
          <el-radio-button label="">全部</el-radio-button>
          <el-radio-button :label="1">常用项目</el-radio-button>
          <el-radio-button :label="0">非常用项目</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row v-if="!isBatchEdit" :gutter="10" class="mb-8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          v-hasPermi="['service:config:inspection:add']"
          @click="handleOpen()"
          >新增收费项目</el-button
        >
        <el-button type="success" plain size="mini" @click="batchSetCommon"
          >批量设置常用项目</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-dropdown>
          <el-button type="warning" plain size="mini">
            批量修改价格<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item>
              <el-button
                class="my-5"
                type="danger"
                plain
                size="mini"
                @click.stop="handleBatchPrice"
                >根据类别调整比例</el-button
              >
            </el-dropdown-item>
            <el-dropdown-item>
              <el-button
                class="my-5"
                type="info"
                plain
                size="mini"
                @click.stop="toggleBatchEdit"
                >全屏手动修改价格</el-button
              >
            </el-dropdown-item>
            <el-dropdown-item>
              <el-button
                class="my-5 width100"
                type="primary"
                plain
                size="mini"
                @click.stop="handlePriceHistory"
                >价格变更记录</el-button
              >
            </el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
          >导入</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
    </el-row>

    <el-table
      :data="tableList"
      v-loading="loading"
      ref="table"
      border
      style="width: 100%; margin-top: 20px"
    >
      <el-table-column type="selection" width="55" key="selection">
      </el-table-column>
      <el-table-column
        label="项目名称"
        prop="itemName"
        align="center"
        key="itemName"
      ></el-table-column>
      <el-table-column
        v-if="!isBatchEdit"
        label="项目首字母"
        prop="itemPinyin"
        align="center"
        width="140"
        key="itemPinyin"
      ></el-table-column>
      <el-table-column
        label="项目编码"
        prop="itemCode"
        align="center"
        width="150"
        key="itemCode"
      ></el-table-column>
      <el-table-column
        v-if="!isBatchEdit"
        label="平台药品编码"
        prop="platformCode"
        align="center"
        width="140"
        key="platformCode"
      ></el-table-column>
      <el-table-column
        label="项目类别"
        prop="dictLabel"
        align="center"
        key="dictLabel"
      ></el-table-column>
      <el-table-column label="服务归属" align="center" key="serviceItems">
        <template slot-scope="{ row }">
          <dict-tag
            :options="dict.type.service_items"
            :value="row.serviceItems"
          />
        </template>
      </el-table-column>
      <el-table-column
        v-if="!isBatchEdit"
        label="项目规格"
        prop="itemSpecs"
        align="center"
        key="itemSpecs"
      ></el-table-column>
      <el-table-column label="项目售价" key="checkPrice" align="center">
        <template slot-scope="{ row }">
          <div v-if="!isBatchEdit">￥{{ row.checkPrice }}</div>
          <el-input-number
            v-else
            v-model="row.checkPrice"
            :controls="false"
            :precision="4"
            :step="0.0001"
            style="width: 100%"
            :min="0"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="项目采购价"
        key="purchasePrice"
        align="center"
        width="140"
      >
        <template slot-scope="{ row }">
          <div v-if="!isBatchEdit">￥{{ row.purchasePrice }}</div>
          <el-input-number
            v-else
            v-model="row.purchasePrice"
            :controls="false"
            :precision="4"
            :step="0.0001"
            style="width: 100%"
            :min="0"
          />
        </template>
      </el-table-column>
      <el-table-column
        v-if="!isBatchEdit"
        label="计量单位"
        prop="unit"
        align="center"
        key="unit"
      ></el-table-column>
      <el-table-column
        v-if="!isBatchEdit"
        label="生产厂家"
        prop="produceFactory"
        align="center"
        key="produceFactory"
      ></el-table-column>
      <el-table-column
        v-if="!isBatchEdit"
        label="是否常用项目"
        align="center"
        width="200"
        key="isCommon"
      >
        <template slot-scope="{ row }">
          <el-switch
            v-model="row.isCommon"
            :active-value="1"
            active-text="是"
            :inactive-value="0"
            inactive-text="否"
            @change="rowSetCommon(row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        v-if="!isBatchEdit"
        label="状态"
        align="center"
        width="200"
        key="status"
      >
        <template slot-scope="{ row }">
          <el-switch
            v-model="row.status"
            :active-value="0"
            active-text="启用"
            :inactive-value="1"
            inactive-text="禁用"
            :disabled="upStatusDisabled"
            @change="changeStatus(row)"
          >
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column
        v-if="!isBatchEdit"
        label="创建时间"
        prop="createTime"
        align="center"
        width="180"
        key="createTime"
      ></el-table-column>
      <el-table-column
        v-if="!isBatchEdit"
        label="更新时间"
        prop="updateTime"
        align="center"
        width="180"
        key="updateTime"
      ></el-table-column>
      <el-table-column
        v-if="!isBatchEdit"
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="120px"
        fixed="right"
        key="operation"
      >
        <template slot-scope="{ row }">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            v-hasPermi="['service:config:inspection:edit']"
            @click="handleOpen(row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            v-hasPermi="['service:config:inspection:delete']"
            @click="handDelete(row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-if="!isBatchEdit"
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <EditInspection ref="EditInspection" @refresh="getList" />

    <ImportModal
      ref="ImportModal"
      title="导入收费项目"
      url="/tool/importData/tcm/importItem"
      templateUrl="https://onelive.obs.cn-south-1.myhuaweicloud.com/uniapp/static/%E6%94%B6%E8%B4%B9%E9%A1%B9%E7%9B%AE%E5%AF%BC%E5%85%A5%E6%A8%A1%E7%89%88.xlsx"
      customUpload
      @uploadFile="uploadFile"
    />

    <BatchPrice ref="BatchPrice" @success="getList" />

    <FixedBottomButton v-if="isBatchEdit">
      <el-button type="primary" size="medium" @click="seveBatchEdit" :loading="saveLoading">
        保存并退出
      </el-button>
      <el-button size="medium" @click="toggleBatchEdit">
        退出批量修改
      </el-button>
    </FixedBottomButton>
  </div>
</template>

<script>
import {
  getManageList,
  getCategoryList,
  deleteInspection,
  upInspectionStatus,
  itemSetCommon,
  importItem,
  categoryTree,
  batchUpdatePrice,
  updateInspection
} from "@/api/service";


import { hasPermi } from "@/plugins/auth";
import { blobValidate } from "@/utils/ruoyi";
import { saveAs } from 'file-saver'
import ImportModal from "@/components/importModal";
import EditInspection from './editInspection'
import BatchPrice from './components/batchPrice'
import FixedBottomButton from '@/components/FixedBottomButton'

export default {
  name: "Inspection",
  dicts: ["service_items"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        searchValue: undefined,
        serviceItems: undefined, // 服务归属
        dictCode: undefined, // 项目类别
        status: undefined, // 状态
        isCommon: "",
      },
      classList: [],
      tableList: [],
      isBatchEdit: false, // 是否为批量修改模式
      originalTableList: [], // 保存原始数据的副本
      modifiedRows: [], // 存储修改过的数据
      batchEditParams: { // 批量编辑模式的分页参数
        pageNum: 1, // 当前页码
        pageSize: 20, // 每页数量
        hasMore: true, // 是否还有更多数据
      },
      scrollContainer: null, // 添加滚动容器引用
      isLoadingMore: false, // 添加标记，防止重复加载
      saveLoading: false, // loading状态 - 保存按钮loading
    };
  },
  components: {
    ImportModal,
    EditInspection,
    BatchPrice,
    FixedBottomButton
  },
  computed: {
    upStatusDisabled: function () {
      return !hasPermi("service:config:inspection:upStatus");
    },
  },
  created() {
    this.getList();
  },
  activated() {
    this.getList();
  },
  mounted() {
    // 获取正确的滚动容器
    this.scrollContainer = document.querySelector('.app-container');
    if (this.scrollContainer) {
      this.scrollContainer.addEventListener('scroll', this.handleScroll);
    }
  },
  beforeDestroy() {
    // 移除滚动监听
    if (this.scrollContainer) {
      this.scrollContainer.removeEventListener('scroll', this.handleScroll);
    }
  },
  methods: {
    async getList() {
      const params = {
        ...this.queryParams,
        pageNum: this.isBatchEdit ? this.batchEditParams.pageNum : this.queryParams.pageNum,
        pageSize: this.isBatchEdit ? this.batchEditParams.pageSize : this.queryParams.pageSize
      };

      try {
        this.loading = !this.isLoadingMore; // 只在非加载更多时显示loading
        const response = await getManageList(params);

        if (this.isBatchEdit) {
          // 批量编辑模式下追加数据
          if (this.batchEditParams.pageNum === 1) {
            this.tableList = response.rows;
            // 第一页时重置原始数据
            this.originalTableList = JSON.parse(JSON.stringify(response.rows));
          } else {
            this.tableList = [...this.tableList, ...response.rows];
            // 追加新数据到原始数据
            this.originalTableList = [...this.originalTableList, ...JSON.parse(JSON.stringify(response.rows))];
          }

          // 判断是否还有更多数据
          this.batchEditParams.hasMore = response.rows.length === this.batchEditParams.pageSize;
        } else {
          // 普通模式直接替换数据
          this.tableList = response.rows;
        }

        this.total = response.total;
        this.loading = false;
      } catch (error) {
        console.error('获取列表失败:', error);
        this.loading = false;
        throw error; // 向上传递错误
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.batchEditParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    handleOpen(row) {
      this.$refs.EditInspection.openModal(row);
    },

    // 表格筛选-查询项目类别列表
    async serviceItemsQuery() {
      this.queryParams.dictCode = "";
      this.handleQuery();

      if (!this.queryParams.serviceItems) return;

      const { data } = await categoryTree({ serviceItems: this.queryParams.serviceItems });
      if (data.length) {
        this.classList = data;
        return
      }
      const { rows } = await getCategoryList({
        serviceItems: this.queryParams.serviceItems,
        pageSize: 9999,
      });
      this.classList = rows.map(v => {
        return {
          categoryId: v.dictCode,
          categoryName: v.dictLabel
        }
      });
    },
    // 删除
    handDelete(row) {
      this.$confirm("是否确认删除该项目？", "确认", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        let params = {
          itemIds: [row.itemId],
          dictCode: row.dictCode,
        };
        deleteInspection(params).then(() => {
          this.$message.success("删除成功");
          this.getList();
        });
      });
    },
    // 修改状态
    changeStatus(row) {
      let params = {
        itemIds: [row.itemId],
        status: row.status,
      };
      upInspectionStatus(params).then((res) => {
        this.$message.success("操作成功");
        this.getList();
      });
    },

    rowSetCommon(row) {
      const params = {
        itemIds: [row.itemId],
        isCommon: row.isCommon,
      };
      itemSetCommon(params)
        .then(() => {
          this.$message.success("设置成功");
        })
        .catch((err) => {
          row.isCommon = row.isCommon ? 0 : 1; // 设置失败,复位
        });
    },
    batchSetCommon() {
      const params = {
        itemIds: this.$refs.table.selection.map((v) => v.itemId),
        isCommon: 1,
      };
      if (!params.itemIds.length) {
        this.$message.error("请勾选需要设置的项目");
        return;
      }
      itemSetCommon(params).then(() => {
        this.getList();
        this.$message.success("设置成功");
      });
    },



    /** 导入按钮操作 */
    handleImport() {
      this.$refs.ImportModal.openModal();
    },
    async uploadFile(file) {
      const that = this;
      let params = new FormData()
      params.append('file', file);
      that.$refs.ImportModal.upload.isUploading = true; // 上传中
      const res = await importItem(params);
      const isBlob = await blobValidate(res);
      if (isBlob) {
        const blob = new Blob([res]);
        saveAs(blob, '导入失败项目.xlsx');
      } else if (res.type == 'application/json') { // 返回的blob类型,转为json
        const reader = new FileReader();
        reader.readAsText(res, 'utf-8');
        reader.onload = function () {
          const { code } = JSON.parse(reader.result);
          code === 200 ? that.$message.success('上传成功') : that.$message.error('上传失败,请检查文件')
        }
      }
      that.resetQuery();
      that.$refs.ImportModal.upload.open = false;
      that.$refs.ImportModal.upload.isUploading = false; // 上传完成
      that.$refs.ImportModal.$refs.upload.clearFiles();
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "check/project",
        {
          ...this.queryParams,
        },
        `收费项目_${this.parseTime(new Date(), "{y}-{m}-{d}")}.xlsx`
      );
    },
    // 打开批量修改价格弹窗
    handleBatchPrice() {
      this.$refs.BatchPrice.openModal();
    },
    // 检查修改的数据
    checkModifiedData(returnData = false) {
      const modifiedRows = this.tableList.filter((row) => {
        // 通过 itemId 查找对应的原始数据
        const originalRow = this.originalTableList.find(
          (original) => original.itemId === row.itemId
        );

        if (!originalRow) return false; // 如果找不到原始数据，不算作修改

        // 转换为固定精度的字符串进行比较，避免浮点数精度问题
        const originalCheckPrice = Number(originalRow.checkPrice).toFixed(4);
        const originalPurchasePrice = Number(originalRow.purchasePrice).toFixed(4);
        const currentCheckPrice = Number(row.checkPrice).toFixed(4);
        const currentPurchasePrice = Number(row.purchasePrice).toFixed(4);

        // 比较转换后的字符串
        const checkPriceChanged = originalCheckPrice !== currentCheckPrice;
        const purchasePriceChanged = originalPurchasePrice !== currentPurchasePrice;

        return checkPriceChanged || purchasePriceChanged;
      });

      if (returnData) {
        return modifiedRows.map(row => ({
          itemId: row.itemId,
          checkPrice: Number(row.checkPrice),
          purchasePrice: Number(row.purchasePrice)
        }));
      }

      return modifiedRows.length > 0;
    },

    // 修改加载更多数据方法
    async loadMoreData() {
      if (this.loading || this.isLoadingMore) return;

      this.isLoadingMore = true;
      const container = this.scrollContainer;

      // 记录当前视图中最后一个元素
      const lastVisibleRow = this.getLastVisibleRow();
      if (!lastVisibleRow) {
        this.isLoadingMore = false;
        return;
      }

      try {
        this.batchEditParams.pageNum += 1;
        await this.getList();

        // 等待 DOM 更新
        await this.$nextTick();

        // 找到之前记录的最后一个元素的新位置
        const lastVisibleElement = this.findRowElement(lastVisibleRow.itemId);
        if (lastVisibleElement) {
          // 将这个元素滚动到视图顶部附近（预留一些上方空间）
          const offset = 150; // 预留150px的上方空间
          const targetScrollTop = lastVisibleElement.offsetTop - offset;

          container.scrollTo({
            top: targetScrollTop,
            behavior: 'smooth'
          });
        }
      } catch (error) {
        console.error('加载更多数据失败:', error);
      } finally {
        this.isLoadingMore = false;
      }
    },

    // 获取视图中最后一个完全可见的行元素
    getLastVisibleRow() {
      const container = this.scrollContainer;
      const rows = this.$refs.table.$el.querySelectorAll('.el-table__row');
      const containerRect = container.getBoundingClientRect();

      let lastVisibleRow = null;
      let lastVisibleRowData = null;

      for (const row of rows) {
        const rowRect = row.getBoundingClientRect();
        // 检查行是否在视图中
        if (rowRect.top <= containerRect.bottom) {
          lastVisibleRow = row;
          // 获取行对应的数据
          const rowIndex = Array.from(rows).indexOf(lastVisibleRow);
          lastVisibleRowData = this.tableList[rowIndex];
        } else {
          break;
        }
      }

      return lastVisibleRowData;
    },

    // 根据itemId查找对应的DOM元素
    findRowElement(itemId) {
      const rows = this.$refs.table.$el.querySelectorAll('.el-table__row');
      for (let i = 0; i < rows.length; i++) {
        if (this.tableList[i] && this.tableList[i].itemId === itemId) {
          return rows[i];
        }
      }
      return null;
    },

    // 修改滚动处理方法，调整触发距离
    handleScroll() {
      if (!this.isBatchEdit || !this.batchEditParams.hasMore || this.loading || this.isLoadingMore) return;

      const container = this.scrollContainer;
      if (!container) return;

      const scrollHeight = container.scrollHeight;
      const scrollTop = container.scrollTop;
      const clientHeight = container.clientHeight;

      // 调整触发距离为200px
      if (scrollHeight - scrollTop - clientHeight < 200) {
        this.loadMoreData();
      }
    },

    // 修改 toggleBatchEdit 方法
    async toggleBatchEdit() {
      if (!this.isBatchEdit) {
        // 进入批量编辑模式
        this.isBatchEdit = true;
        this.batchEditParams = {
          pageNum: 1,
          pageSize: 20,
          hasMore: true
        };
        await this.getList();

        // 重置滚动位置
        if (this.scrollContainer) {
          this.scrollContainer.scrollTop = 0;
        }
      } else {
        // 退出批量编辑模式
        if (this.checkModifiedData()) {
          try {
            await this.$confirm('有未保存的修改，是否确认退出？', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            });
            this.exitBatchEdit();
          } catch (err) {
            // 用户取消退出
          }
        } else {
          this.exitBatchEdit();
        }
      }
    },

    // 修改 exitBatchEdit 方法
    exitBatchEdit() {
      this.isBatchEdit = false;
      this.batchEditParams = {
        pageNum: 1,
        pageSize: 20,
        hasMore: true
      };
      // 重置滚动位置
      if (this.scrollContainer) {
        this.scrollContainer.scrollTop = 0;
      }
      this.getList();
    },

    // 保存并退出
    async seveBatchEdit() {
      const modifiedData = this.checkModifiedData(true); // 获取修改数据

      if (modifiedData.length === 0) {
        this.$message.info('没有需要保存的修改');
        this.isBatchEdit = false;
        this.getList();
        return;
      }

      try {
        await this.$confirm(`确认保存 ${modifiedData.length} 条修改记录？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });

        // 构造新的请求参数
        const updateItemList = modifiedData.map(item => {
          const originalItem = this.originalTableList.find(
            original => original.itemId === item.itemId
          );

          return {
            itemId: item.itemId, // 项目ID
            itemCode: originalItem.itemCode, // 项目编码
            itemName: originalItem.itemName, // 项目名称
            dictLabel: originalItem.dictLabel, // 项目类别
            checkPrice: item.checkPrice, // 新售价
            purchasePrice: item.purchasePrice, // 新采购价
            oldCheckPrice: originalItem.checkPrice, // 原售价
            oldPurchasePrice: originalItem.purchasePrice // 原采购价
          };
        });

        const params = {
          updateType: 1, // 1表示直接修改价格
          updateItemList // 修改的项目列表
        };

        this.saveLoading = true; // 开始loading
        // 调用批量更新接口
        await batchUpdatePrice(params);

        this.$message.success('保存成功');
        this.isBatchEdit = false;
        this.getList();
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('保存失败');
        }
      } finally {
        this.saveLoading = false; // 结束loading
      }
    },

    // 添加新方法
    handlePriceHistory() {
      this.$router.push({
        path: '/service/priceHistory/index',
        query: {
          serviceItems: this.queryParams.serviceItems, // 传递当前服务归属
          dictCode: this.queryParams.dictCode // 传递当前项目类别
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  padding-bottom: 60px; // 为固定底部按钮留出空间
  height: calc(100vh - 84px); // 设置容器高度
  overflow-y: auto; // 启用容器滚动
  scroll-behavior: smooth; // 添加平滑滚动效果
}
</style>
